package com.hengxinguotong.zhihuichengjian.ui.device;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.Device;
import com.hengxinguotong.zhihuichengjian.bean.DeviceListRes;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.ScanningActivity;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by liux on 2017/3/13.
 */

public class DeviceMainTainFragment extends BaseFragment implements AualityTestAddPicAdapter.OnRecyclerViewClickListener {
    @BindView(R.id.select_ll)
    LinearLayout selectLl;
    @BindView(R.id.name_etv)
    HXEditTextView nameEtv;
    @BindView(R.id.number_etv)
    HXEditTextView numberEtv;
    @BindView(R.id.position_rl)
    RelativeLayout positionRl;
    @BindView(R.id.model_etv)
    HXEditTextView modelEtv;
    @BindView(R.id.profession_rl)
    RelativeLayout professionRl;
    @BindView(R.id.manufactor_etv)
    HXEditTextView manufactorEtv;
    @BindView(R.id.date_tv)
    HXTextView dateTv;
    @BindView(R.id.date_label)
    HXTextView dateLabel;
    @BindView(R.id.no_pic_tv)
    HXTextView noPicTv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;
    @BindView(R.id.remarks_etv)
    HXEditTextView remarksEtv;
    @BindView(R.id.leasing_company_etv)
    HXEditTextView leasingCompanyEtv;
    Unbinder unbinder;
    private AualityTestAddPicAdapter addPicAdapter;
    private List<String> paths;
    private List<String> minPaths;
    private String deviceId;  //设备id  扫描时获得
    private final int GETDATE = 1001;
    private final int GETCODE = 1002;
    private final int GETDEVICE = 1003;
    private Device device;
    private int year = 0;
    private int monthOfYear = 0;
    private int dayOfMonth = 0;
    public static String deviceType;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_devicemaintain, null);
        unbinder = ButterKnife.bind(this, contentView);
        initView();
        return contentView;
    }

    @Override
    public void onLazyLoad() {

    }

    private void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        paths = new ArrayList<String>();
        paths.add(Utils.ADDPIC);
        addPicAdapter = new AualityTestAddPicAdapter(getActivity(), paths, this, true);
        addPicRv.setLayoutManager(linearLayoutManager);
        addPicRv.setAdapter(addPicAdapter);
        if (device != null) {
            selectLl.setVisibility(View.GONE);
            Utils.setEditTextViewUnable(device.getName(), nameEtv);
            Utils.setEditTextViewUnable(device.getNumber(), numberEtv);
            Utils.setEditTextViewUnable(device.getModel(), modelEtv);
            Utils.setEditTextViewUnable(device.getManufacturer(), manufactorEtv);
            Utils.setEditTextViewUnable(device.getRemark(), remarksEtv);
            Utils.setEditTextViewUnable(device.getLeasingCompany(), leasingCompanyEtv);
            dateTv.setText(device.getCreateTime());
            dateTv.setClickable(false);

            paths = device.getPicList();
            if (paths.size() == 0) {
                noPicTv.setVisibility(View.VISIBLE);
                addPicRv.setVisibility(View.GONE);
            } else {
                addPicAdapter = new AualityTestAddPicAdapter(getActivity(), paths, this, false);
                addPicRv.setAdapter(addPicAdapter);
            }

            remarksEtv.setText(device.getRemark());
            remarksEtv.setEnabled(false);
        }

        Bundle bundle = getArguments();
        deviceType = bundle.getString("type");
        if (DeviceMainTainListActivity.REPAIR.equals(deviceType)) {
            dateLabel.setText("维修日期");
        } else if (DeviceMainTainListActivity.MAINTAIN.equals(deviceType)) {
            dateLabel.setText("保养日期");
        }

        Calendar c = Calendar.getInstance();
        year = c.get(Calendar.YEAR);
        monthOfYear = c.get(Calendar.MONTH);
        dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
        dateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
    }

    public static DeviceMainTainFragment newInstance(String type) {
        DeviceMainTainFragment fragment = new DeviceMainTainFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            if (device != null) {
                TaskBigImgActivity.startActivity(getActivity(), (ArrayList<String>) paths, position);
            } else {
                paths.remove(position);
                addPicAdapter.notifyDataSetChanged();
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            if (requestCode == 1) {
                paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                paths.add(Utils.ADDPIC);
                if (addPicAdapter != null) {
                    addPicAdapter.setPaths(paths);
                }
            } else if (requestCode == GETDEVICE) {
                device = (Device) data.getExtras().get("device");
                deviceId = device.getId();
                reloadViews(device);
            } else if (requestCode == GETCODE) {
//            String code = data.getStringExtra("code");
//            if (code.contains("_")) {
//                deviceId = code.split("_")[1];
//                getDeviceInfo(getResources().getString(R.string.loading));
//            }
                String QRcode = data.getStringExtra("QRcode");
                if(QRcode.contains("_")){
                    deviceId = QRcode.split("_")[1];
                }else{
                    deviceId = QRcode;
                }
                numberEtv.setText(QRcode);
                getDeviceInfo(getResources().getString(R.string.loading));
            }
        }

    }


    public void setData(Device device) {
        this.device = device;
    }

    private void getDeviceInfo(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("equipmentId", deviceId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/equipmentRegister/queryList/" + SPUtil.getString(getActivity(),"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    DeviceListRes deviceListRes = gson.fromJson(json, DeviceListRes.class);
                    if (deviceListRes.getValue().size() == 1) {
                        reloadViews(deviceListRes.getValue().get(0));
                    }
                }

            }

            @Override
            public void onFailure(String json) {

            }
        });
    }


    private void reloadViews(Device device) {
        Utils.setEditTextViewHint(device.getName(), nameEtv);
        Utils.setEditTextViewHint(device.getNumber(), numberEtv);
        Utils.setEditTextViewHint(device.getModel(), modelEtv);
        Utils.setEditTextViewHint(device.getManufacturer(), manufactorEtv);
        Utils.setEditTextViewHint(device.getLeasingCompany(), leasingCompanyEtv);
    }

    private boolean checkText() {
        if (Utils.isEmpty(deviceId)) {
            ((BaseActivity) getActivity()).showToast("请扫描机器上的二维码或选择设备列表");
            return false;
        }

        return true;
    }


    public void getMinImage(final String type) {
        if (!checkText()) {
            return;
        }

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), getActivity());

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    deviceInorOut(type);
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            deviceInorOut(type);
        }

    }

    private void deviceInorOut(String type) {
        RequestParams params = new RequestParams();
        params.addBodyParameter("equipmentId", deviceId);
        params.addBodyParameter("constructionId", SPUtil.getString(getActivity(),"constructionid"));
        params.addBodyParameter("createBy", SPUtil.getString(getActivity(), "userId"));
        params.addBodyParameter("remark", remarksEtv.getEditableText().toString());
        params.addBodyParameter("date", year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);

        for (int i = 0; i < minPaths.size(); i++) {
            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
        }
        params.addBodyParameter("type", type);

        Utils.requestData(getResources().getString(R.string.loading), getActivity(), "/equipmentRegister/saveEquipmentMaintenance/" + SPUtil.getString(getActivity(),"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    ((BaseActivity) getActivity()).showToast("提交成功");
                    getActivity().setResult(1);
                    getActivity().finish();
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    @OnClick({ R.id.scan_rl, R.id.list_rl, R.id.date_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.scan_rl:
//                intent = new Intent(getActivity(), CaptureActivity.class);
                intent = new Intent(getActivity(), ScanningActivity.class);
                startActivityForResult(intent, GETCODE);
                break;
            case R.id.list_rl:
                intent = new Intent(getActivity(), DeviceSelectedActivity.class);
                startActivityForResult(intent, GETDEVICE);
                break;
            case R.id.date_tv:
                showWheelViewDialog();
                break;
        }
    }

    private void showWheelViewDialog() {
        new DatePickerDialog(getActivity(),
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        DeviceMainTainFragment.this.year = year;
                        DeviceMainTainFragment.this.monthOfYear = monthOfYear;
                        DeviceMainTainFragment.this.dayOfMonth = dayOfMonth;
                        dateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                year, monthOfYear, dayOfMonth).show();
    }
}
